package service

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"math"
	"net/http"
	"strconv"
	"strings"
	"time"
	"yuce/entrys"
)

type Jisuan struct {
}

// 定义计算函数类型
type CalculationFunc func(string, bool) int

func (j *Jisuan) SinNum(f CalculationFunc, isFront bool) []entrys.PredictionResult {
	url := "https://lottery.yabo28.net/api/v1/open/history?lotCode=2"
	resp, err := http.Get(url)
	if err != nil {
		fmt.Println("Error fetching URL:", err)
		return nil
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("Error reading response body:", err)
		return nil
	}
	var response entrys.LotteryData
	err = json.Unmarshal(body, &response)
	if err != nil {
		fmt.Println("Error unmarshaling JSON:", err)
		return nil
	}
	// 初始化前一个opencode的大小和单双属性
	var previousSize, previousOddEven, previousOpencode string
	var previousOpenTime time.Time
	var results []entrys.PredictionResult
	for i, item := range response.Data {
		// 获取opencode的内容并去除逗号
		opencodeStr := strings.ReplaceAll(item.Content, ",", "")
		// 计算sin值并确定大小和单双属性
		//sinSum := calculateSin(opencodeStr)
		sums := f(opencodeStr, isFront)
		currentSize := determineSize(sums)
		currentOddEven := determineOddEven(sums)
		var result entrys.PredictionResult
		if i > 0 {
			// 与前一个opencode比较，并打印结果
			sizeCorrect := (currentSize == previousSize)
			oddEvenCorrect := (currentOddEven == previousOddEven)
			result = entrys.PredictionResult{
				CurrentOpencode:  item.Content,
				PredictedSum:     sums,
				CurrentOpenTime:  item.OpenTime,
				PreviousOpencode: previousOpencode,
				PreviousOpenTime: previousOpenTime.Format("15:04:05"),
				PredictedSize:    currentSize,
				SizeCorrect:      sizeCorrect,
				PredictedOddEven: currentOddEven,
				OddEvenCorrect:   oddEvenCorrect,
			}
			//fmt.Printf("当前Opencode: %s,预测结果%v 开奖时间: %s\n", item.Content, sums, item.OpenTime)
			//fmt.Printf("比较Opencode: %s, 开奖时间: %s\n", previousOpencode, previousOpenTime.Format("15:04:05"))
			//fmt.Printf("预测大小: %s,%t 预测单双: %s,%t\n\n", currentSize, sizeCorrect, currentOddEven, oddEvenCorrect)

		} else {
			result = entrys.PredictionResult{
				CurrentOpencode:  item.Content,
				PredictedSum:     sums,
				CurrentOpenTime:  item.OpenTime,
				PredictedSize:    currentSize,
				PredictedOddEven: currentOddEven,
			}
			// 如果是第一个数据，没有前一个opencode，则输出当前预测内容
			//fmt.Printf("当前Opencode: %s,预测结果%v 开奖时间: %s\n", item.Content, sums, item.OpenTime)
			//fmt.Printf("预测大小: %s, 预测单双: %s\n\n", currentSize, currentOddEven)
		}
		results = append(results, result)
		// 更新前一个opencode的属性和内容
		previousSize = determineSize(calculateSum(item.Content))       // 使用当前Opencode的大小
		previousOddEven = determineOddEven(calculateSum(item.Content)) // 使用当前Opencode的单双
		previousOpencode = item.Content
		previousOpenTime, _ = time.Parse("2006-01-02 15:04:05", item.OpenTime)
	}
	return results
}

// CalculateSin 计算给定字符串数值的sin值，并根据isFront获取小数部分前三位或后三位数字之和
func CalculateSin(value string, isFront bool) int {
	// 将字符串转换为整数
	num, err := strconv.Atoi(value)
	if err != nil {
		fmt.Println("Error converting string to int:", err)
		return 0
	}
	// 计算该数字的余弦值
	cosValue := math.Sin(float64(num))
	// 将结果转换为字符串
	cosStr := fmt.Sprintf("%.10f", cosValue)
	// 获取小数部分
	parts := strings.Split(cosStr, ".")
	if len(parts) < 2 {
		return 0
	}
	fractionalPart := parts[1]
	if len(fractionalPart) < 3 {
		fractionalPart += strings.Repeat("0", 3-len(fractionalPart))
	}

	var digits string
	if isFront {
		digits = fractionalPart[:3] // 获取前三位
	} else {
		digits = fractionalPart[len(fractionalPart)-3:] // 获取后三位
	}

	// 将选定的三位数字求和
	sum := 0
	for _, digit := range digits {
		digitInt, _ := strconv.Atoi(string(digit))
		sum += digitInt
	}
	return sum
}
func GetDecimalSum(value string, isFront bool) int {
	// 将字符串转换为整数
	num, err := strconv.Atoi(value)
	if err != nil {
		fmt.Println("Error converting string to int:", err)
		return 0
	}
	// 计算该数字的余弦值
	cosValue := math.Sqrt(float64(num))
	// 将结果转换为字符串
	cosStr := fmt.Sprintf("%.10f", cosValue)
	// 获取小数部分
	parts := strings.Split(cosStr, ".")
	if len(parts) < 2 {
		return 0
	}
	fractionalPart := parts[1]
	if len(fractionalPart) < 3 {
		fractionalPart += strings.Repeat("0", 3-len(fractionalPart))
	}

	var digits string
	if isFront {
		digits = fractionalPart[:3] // 获取前三位
	} else {
		digits = fractionalPart[len(fractionalPart)-3:] // 获取后三位
	}

	// 将选定的三位数字求和
	sum := 0
	for _, digit := range digits {
		digitInt, _ := strconv.Atoi(string(digit))
		sum += digitInt
	}
	return sum
}

// CalculateCos 计算给定字符串数值的cos值，并根据isFront获取小数部分前三位或后三位数字之和
func CalculateCos(value string, isFront bool) int {
	// 将字符串转换为整数
	num, err := strconv.Atoi(value)
	if err != nil {
		fmt.Println("Error converting string to int:", err)
		return 0
	}
	// 计算该数字的余弦值
	cosValue := math.Cos(float64(num))
	// 将结果转换为字符串
	cosStr := fmt.Sprintf("%.10f", cosValue)
	// 获取小数部分
	parts := strings.Split(cosStr, ".")
	if len(parts) < 2 {
		return 0
	}
	fractionalPart := parts[1]
	if len(fractionalPart) < 3 {
		fractionalPart += strings.Repeat("0", 3-len(fractionalPart))
	}

	var digits string
	if isFront {
		digits = fractionalPart[:3] // 获取前三位
	} else {
		digits = fractionalPart[len(fractionalPart)-3:] // 获取后三位
	}

	// 将选定的三位数字求和
	sum := 0
	for _, digit := range digits {
		digitInt, _ := strconv.Atoi(string(digit))
		sum += digitInt
	}
	return sum
}
func GetLogNumvalue(value string, isFront bool) int {
	// 将字符串转换为整数
	num, err := strconv.Atoi(value)
	if err != nil {
		fmt.Println("Error converting string to int:", err)
		return 0
	}
	// 计算该数字的余弦值
	cosValue := math.Log10(float64(num))
	// 将结果转换为字符串
	cosStr := fmt.Sprintf("%.10f", cosValue)
	// 获取小数部分
	parts := strings.Split(cosStr, ".")
	if len(parts) < 2 {
		return 0
	}
	fractionalPart := parts[1]
	if len(fractionalPart) < 3 {
		fractionalPart += strings.Repeat("0", 3-len(fractionalPart))
	}

	var digits string
	if isFront {
		digits = fractionalPart[:3] // 获取前三位
	} else {
		digits = fractionalPart[len(fractionalPart)-3:] // 获取后三位
	}

	// 将选定的三位数字求和
	sum := 0
	for _, digit := range digits {
		digitInt, _ := strconv.Atoi(string(digit))
		sum += digitInt
	}
	return sum
}
func determineSize(value int) string {
	if value >= 0 && value <= 13 {
		return "小"
	}
	return "大"
}

func determineOddEven(value int) string {
	if value%2 == 0 {
		return "双"
	}
	return "单"
}

// 计算opencode的和值
func calculateSum(opencode string) int {
	numbers := strings.Split(opencode, ",")
	sum := 0
	for _, num := range numbers {
		val, _ := strconv.Atoi(num)
		sum += val
	}
	return sum
}
